<?php

namespace App\Http\Controllers\Wap;

use App\Models\Configs;
use App\Models\Users;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Laravel\Socialite\Facades\Socialite;
use Mrgoon\AliSms\AliSms;
use Illuminate\Foundation\Auth\AuthenticatesUsers;

class AuthController extends Controller
{
    use AuthenticatesUsers;

    protected $chanel_id = 3;//设置导航选中标志

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
        view()->share('chanel_id',$this->chanel_id);
    }

    public function three(Request $request){
        $data = $request->all();
        cache()->add('three',$data,10*60);
        return $this->writeJson(0);
    }

    public function login(Request $request)
    {
        if($request->method() == 'POST'){
            $data = $request->all();
            $three = cache()->get('three');
            $credentials['username'] = $data['username'];
            $credentials['password'] = $data['password'];
            if ($this->guard()->attempt($credentials, $request->has('remember'))) {
                $request->session()->regenerate();
                $this->clearLoginAttempts($request);
                $update = [
                    'login_ip' => $request->ip(),
                    'login_at' => Carbon::now(),
                ];
                if(isset($three['type'])){
                    switch($three['type']){
                        case 'weibo':
                            $update['weibo_id'] = $three['three_id'];
                            break;
                        case 'qq':
                            $update['qq_id'] = $three['three_id'];
                            break;
                    }
                }
                auth()->user()->update($update);
                $previous = route('wap.user.index');
                return $this->writeJson(0,$previous);
            }
            return $this->writeJson(1,null,'账号或者密码错误');
        }else{
            $target = url()->previous();
            return view('wap.auth.login',compact('target'));
        }
    }

    public function register(Request $request)
    {
        if($request->method() == 'POST'){
            $data = $request->all();
            $three = cache()->get('three');
            //验证短信验证码
            $cache = cache()->get('sms-'.$data['username']);
            //过期
            if(empty($cache)) return $this->writeJson(1,null,'验证码已过期');
            //正确
            if($cache['code'] != $data['code']) return $this->writeJson(1,null,'验证码输入错误');
            //删除
            cache()->delete('sms-'.$data['username']);

            //字段验证
            $rules = [
                'username' => 'required|unique:users',
                'code'     => 'required',
                'password' => 'required|min:6|confirmed',
                'email'    => 'required|email|unique:users',
            ];
            $msgs = [
                'username.required' => '请填写手机号码',
                'username.unique'   => '手机号已经注册',
                'code.required'     => '请填写短信验证码',
                'password.required' => '请输入密码',
                'password.min'      => '密码最少6位',
                'password.confirmed'=> '确认密码不一致',
                'email.required'    => '请填写邮箱账号',
                'email.email'       => '邮箱账号格式错误',
                'email.unique'      => '邮箱账号已经存在',
            ];
            $validator = validator()->make($data, $rules ,$msgs);
            if ($validator->fails()) {
                return $this->writeJson(1,null,$validator->errors()->first());
            }
            //获取积分规则
            $setting = Configs::info('integral');
            $webSetting = Configs::info('setting');
            $insert = $data;
            $insert['password'] = bcrypt($insert['password']);
            $insert['register_ip']= $request->ip();
            $insert['name']      = $three['name'] ?? $this->randName();
            $insert['avatar'] = isset($three['avatar']) ? urldecode($three['avatar']) : $webSetting['default_avatar'];
            $insert['integral']  = $setting['register'];
            $insert['login_at']  = Carbon::now();
            $insert['login_ip']  = $request->ip();
            if(isset($three['type'])){
                switch($three['type']){
                    case 'weibo':
                        $insert['weibo_id'] = $three['three_id'];
                        break;
                    case 'qq':
                        $insert['qq_id'] = $three['three_id'];
                        break;
                }
            }
            $resault = Users::create($insert);
            if($resault === false){
                return $this->writeJson(1,null,'注册失败');
            }else{
                $credentials['username'] = $data['username'];
                $credentials['password'] = $data['password'];
                if ($this->guard()->attempt($credentials, $request->has('remember'))) {
                    $request->session()->regenerate();
                    return $this->writeJson(0,route('wap.user.index'));
                }
            }
        }else{
            return view('wap.auth.register');
        }

    }

    public function sms(Request $request)
    {
        try{
            $type = $request->get('type','');
            $info = Users::where('username',$request->mobile)->first();
            if(empty($type)){
                //验证重复性
                if($info) return $this->writeJson(1,null,'该手机账号已注册');
            }else{
                if(!$info) return $this->writeJson(1,null,'手机账号不存在');
            }
            $cache = cache()->get('sms-'.$request->mobile);
            //20秒的频繁验证
            if($cache && Carbon::now()->timestamp - $cache['time'] < 20){
                return $this->writeJson(1,null,'您的操作太频繁');
            }
            $code = rand(100000,999999);//SMS_141730025  异地登录提醒     SMS_141730027  注册验证码
            $result = (new AliSms())->sendSms($request->mobile, 'SMS_141730027', ['code'=> $code]);
            if($result->Code == 'OK'){
                //保存验证码到缓存用于验证
                $time = Carbon::now()->timestamp;
                //2分钟的过期时间
                cache()->add('sms-'.$request->mobile,['code'=>$code,'time'=>$time],120);
                return $this->writeJson(0);
            }else{
                return $this->writeJson(1,$result,'发送短信失败');
            }
        }catch(\Exception $e){
            return $this->writeJson(1,null,'发送短信失败');
        }
    }


    public function find(Request $request){

        if($request->method() == 'POST'){
            $data = $request->all();
            $user = Users::where('username',$data['username'])->first();
            if(empty($user)) return $this->writeJson(1,null,'手机账号不存在');

            //验证短信验证码
            $cache = cache()->get('sms-'.$data['username']);
            //过期
            if(empty($cache)) return $this->writeJson(1,null,'验证码已过期');
            //正确
            if($cache['code'] != $data['code']) return $this->writeJson(1,null,'验证码输入错误');
            //删除
            cache()->delete('sms-'.$data['username']);

            //字段验证
            $rules = [
                'username' => 'required',
                'code'     => 'required',
                'password' => 'required|min:6|confirmed',
            ];
            $msgs = [
                'username.required' => '请填写手机号码',
                'code.required'     => '请填写短信验证码',
                'password.required' => '请输入新密码',
                'password.min'      => '密码最少6位',
                'password.confirmed'=> '确认密码不一致',
            ];
            $validator = validator()->make($data, $rules ,$msgs);
            if ($validator->fails()) {
                return $this->writeJson(1,null,$validator->errors()->first());
            }
            $user->update(['password'=>bcrypt($data['password'])]);
            return $this->writeJson(0,route('wap.auth.login'));
        }else{
            return view('wap.auth.find');
        }
    }


    /**
     * 退出登录
     * @param Request $request
     * @return mixed
     */
    public function logout()
    {
        $this->guard()->logout();
        request()->session()->regenerate();
        return redirect(route('wap.auth.login'));
    }


    protected function randName(){
        $str = "1234567890qwertyuiopasdfghjklzxcvbnm";
        return substr(str_shuffle($str),mt_rand(0,strlen($str)-11),10);
    }


}